package com.qianniu.napi.common;

import com.alibaba.fastjson.JSON;
import com.qianniu.napi.admin.entity.Role;
import com.qianniu.napi.admin.entity.User;
import com.qianniu.napi.admin.service.IUserService;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by chenxuebin on 2017/3/6.
 */
public class ShiroRealm extends AuthorizingRealm {

    private Logger logger = LoggerFactory.getLogger(ShiroRealm.class);

    @Autowired
    private IUserService userService;

    /**
     * 登录认证
     *
     * @param tk
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken tk) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) tk;
        logger.info("======doGetAuthenticationInfo tk：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
        //查出是否有此用户
        User user = userService.findByName(token.getUsername());
//        String md5Pwd = new Md5Hash("123", "lucare",2).toString();
        if (user != null) {
            // 若存在，将此用户存放到登录认证info中，无需自己做密码对比，
            // Shiro会为我们进行密码对比校验
            List<Role> list = userService.findRolePermissions(user.getId());
            user.setRoleList(list);
            logger.debug(">>>Role list="+JSON.toJSONString(list));
            logger.debug(">>>user ="+JSON.toJSONString(user));
//            return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
            //1)user：认证的实体信息，可以是username，也可以是数据库表对应的用户的实体对象
            //2)credentials：数据库中的密码
            Object credentials = user.getPassword();
            logger.debug(">>>user >>>>>>>>ddd 3");
            //3)realmName：当前realm对象的name，调用父类的getName()方法即可
            String realmName = getName();
            logger.debug(">>>user >>>>>>>>ddd 4");
            //4)user加密的盐值
            ByteSource salt = ByteSource.Util.bytes(user.getSalt());//使用账号作为盐值
            logger.debug(">>>user >>>>>>>>ddd 5");
            //根据用户的情况，来构建AuthenticationInfo对象,通常使用的实现类为SimpleAuthenticationInfo
            //5)与数据库中用户名和密码进行比对，密码盐值加密，第4个参数传入realName。

            SimpleAuthenticationInfo info  = new SimpleAuthenticationInfo(user, credentials, salt, realmName);
            logger.info(">>>>>>装配认证信息【SimpleAuthenticationInfo】 ok and ready to return");
            return info;
        }
        return null;
    }

    /**
     * 权限认证
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("##################执行Shiro权限认证##################");
        //获取当前登录输入的用户名，等价于(String) principalCollection.fromRealm(getName()).iterator().next();
//        String loginName = (String) super.getAvailablePrincipal(principalCollection);
        User user = (User) principalCollection.getPrimaryPrincipal();
        logger.debug(">>>doGetAuthorizationInfo user "+ JSON.toJSONString(user));

//        //到数据库查是否有此对象
//        User user = null;// 实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
//        user = userMapper.findByName(loginName);
        if (user != null) {
            //权限信息对象info,用来存放查出的用户的所有的角色（role）及权限（permission）
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            //用户的角色集合
            for (Role role : user.getRoleList()) {
                info.addRole(role.getName());
                info.addStringPermissions(role.getPerNameSet());
            }
            logger.debug(">>>info "+ JSON.toJSONString(info));
            Session session = SecurityUtils.getSubject().getSession();
            logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>doGetAuthorizationInfo user="+JSON.toJSONString(user));
            session.setAttribute("user", user);
            return info;
        }
        // 返回null的话，就会导致任何用户访问被拦截的请求时，都会自动跳转到unauthorizedUrl指定的地址
        logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>doGetAuthorizationInfo return null ");
        return null;
    }

}
